from datetime import datetime
from db.crud.company import get_company_count, get_company_byname, get_company_byl2id
from schemas.company import CompanyQueryRequest

def transform_data(input_data):
    result = []
    industry_map = {}
    
    for item in input_data:
        id1, name1, sub_id, sub_name, info = item
        
        if id1 not in industry_map:
            industry_map[id1] = {
                "id": id1,
                "name": name1,
                "data": []
            }
            result.append(industry_map[id1])
        
        industry_map[id1]["data"].append({
            "id": sub_id,
            "name": sub_name,
            "info": info
        })
    
    return result

class CompanyService:
    async def get_company_list(self,params:CompanyQueryRequest):
        query_data = params.dict()
        result = dict()
        result['total'] = 0
        result['total_pages'] = 0
        result['page'] = 1 if not query_data.get('page') else query_data.get('page')
        result['page_size'] = 20 if not query_data.get('page_size') else query_data.get('page_size')
        result['data'] = []

        # print(query_data)
        # 检查参数中l2_id和keyword是否至少有一个存在
        if not (query_data.get('l2_id') or query_data.get('keyword')):
            raise ValueError("At least one of l2_id or keyword must be filled.")
        
        """
        if len(query_data[keyword]):
            raise ValueError("At least one of l2_id or keyword must be filled.")
        """
        # 根据条件查询总数量
        total = await get_company_count(query_data['keyword'], query_data['l2_id'])
        if not total.get("total"):
            return result

        result['total'] = total["total"]

        if query_data.get('l2_id'):
            # 根据l2_id条件查询
            data = await get_company_byl2id(query_data['l2_id'], result['page'], result['page_size'])
        else :
            # 根据keyword条件查询
            data = await get_company_byname(query_data["keyword"], result['page'], result['page_size'])

        for row in data:
            result['data'].append({
            "id": str(row[0]),
            "name": row[1],
            "address": row[2],
            "phone": row[3],
            "tags": row[4].split(",") if row[4] else []
        })

        # 计算总页数
        result['total_pages'] = (result['total'] + result['page_size'] - 1) // result['page_size']
        return result